# 输入：文件路径
# 输出：vtkActor
import vtkmodules.all as vtk


class ISTLReader():
    v_reader = vtk.vtkSTLReader()
    v_actor = vtk.vtkActor()
    v_mapper = vtk.vtkDataSetMapper()

    def __init__(self, options=None):
        self._initMapper()
        self.v_actor.SetMapper(self.v_mapper)
        self.poly_data = vtk.vtkPolyData()
        self.outlines = vtk.vtkPolyData()
        self.points = vtk.vtkPolyData()

    def _initMapper(self):
        self.v_mapper.SetInputConnection(self.v_reader.GetOutputPort())

    def SetFileName(self, file_path, force_update=False):
        self.v_reader.SetFileName(file_path)
        if (force_update):
            self.Update()

    def Update(self):
        self.v_reader.Update()
        self.poly_data = self.v_reader.GetOutput()
        self.create_point_data()
        self.create_outlines()

    def GetActor(self):
        print(dir(self.v_actor))
        return self.v_actor

    def create_outlines(self):
        if self.poly_data is None: return
        # todo 生成轮廓线
        # vtk_points = vtk.vtkPoints()
        # for point in self.points:
        #     vtk_points.InsertNextPoint(point.get('XYZ'))

        # # 创建vtkCellArray对象并插入线段
        # lines = vtk.vtkCellArray()
        # num_points = len(self.points)

        # for i in range(num_points):
        #     line = vtk.vtkLine()
        #     print((0,i),(1, (i + 1) % num_points))
        #     line.GetPointIds().SetId(0, i)
        #     line.GetPointIds().SetId(1, (i + 1) % num_points)  # 连成闭环
        #     lines.InsertNextCell(line)

        # # 创建polydata对象并设置点和线段
        # polydata = vtk.vtkPolyData()
        # polydata.SetPoints(vtk_points)
        # polydata.SetLines(lines)
        # self.outlines = polydata

    def create_point_data(self):
        if self.poly_data is None: return

        # 获取顶点坐标
        points = self.poly_data.GetPoints()
        if points is None: return

        num_points = points.GetNumberOfPoints()
        # 创建一个列表来存储顶点坐标
        vertices = []

        for i in range(num_points):
            point = points.GetPoint(i)
            vertices.append({"id": i, "XYZ": point})
        self.points = vertices
